package com.coin900.coin.base.utils;

import com.coin900.coin.base.BxConstants;
import com.sendgrid.*;

import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

/**
 * 邮件工具类
 *
 * @author shui
 * @create 2018-01-22
 **/
public class MailUtils {

    /**
     * 生成邮件 token
     *
     * @return
     */
    public static String buildMailVerifyToken() {
        long currentTimeMillis = System.currentTimeMillis();
        byte[] encode = Base64.getEncoder().encode((currentTimeMillis + UUID.randomUUID().toString()).getBytes());
        String token = new String(encode);
        return token;
    }

    /**
     * sendgrid 发送邮件
     *
     * @param message
     * @param toEmail
     * @param subject
     * @throws IOException
     */
    public static void sendEmail(String message, String toEmail, String subject) throws IOException {
        String fromEmail = BxConstants.SENDGRID_SEND_EMAIL;
        Email from = new Email(fromEmail);
        Email to = new Email(toEmail);
        Content content = new Content("text/plain", message);
        Mail mail = new Mail(from, subject, to, content);
        SendGrid sg = new SendGrid(BxConstants.SENDGRID_API_KEY);
        Request request = new Request();
        try {
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());
            Response response = sg.api(request);
        } catch (IOException ex) {
            throw ex;
        }
    }


    public static void main(String[] args) throws IOException {
        String verifyToken = MailUtils.buildMailVerifyToken();
        String message = "点击链接激活账号" +
                "http://www.fu.coin/coin/activate_mail?verifyToken=" + verifyToken;
        String subject = "激活邮件";
        MailUtils.sendEmail(message,"599504945@qq.com",subject);
    }
}